package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    /**
     * 提交订单
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        System.out.println("orders = {" + orders + "}");

        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> cartqw = new LambdaQueryWrapper<>();
        cartqw.eq(userId!=null,ShoppingCart::getUserId,userId);

        List<ShoppingCart> carts = shoppingCartService.list(cartqw);

        if(carts == null || carts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        List<OrderDetail> details = new ArrayList<>(); //封装订单明细数据

        //使用UUID工具类自动生成ordersID
        Long ordersId = IdWorker.getId();


        //总净额
        BigDecimal amount = new BigDecimal("0");
        for (ShoppingCart cart : carts) {
            OrderDetail detail = new OrderDetail();
            //遍历购物车中每一件商品信息
            BeanUtils.copyProperties(cart,detail,"id");
            detail.setOrderId(ordersId);

            BigDecimal decimal = detail.getAmount().multiply(BigDecimal.valueOf(detail.getNumber()));
            amount = amount.add(decimal);
            //添加至订单明细集合
            details.add(detail);
        }

        //批量保存订单明细数据
        orderDetailService.saveBatch(details);

        //封装订单数据
        List<Orders> ordersList = new ArrayList<>();
        Orders addOrders = new Orders();
        addOrders.setId(ordersId);
        addOrders.setNumber(UUID.randomUUID().toString());
        addOrders.setAddressBookId(orders.getAddressBookId());
        addOrders.setAddress((addressBook.getProvinceName()==null?"":addressBook.getProvinceName())+
                (addressBook.getCityName()==null?"":addressBook.getCityName()) +
                (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())+
                (addressBook.getDistrictName()==null?"":addressBook.getDistrictName()));
        addOrders.setConsignee(addressBook.getConsignee());
        addOrders.setAmount(amount);
        addOrders.setCheckoutTime(LocalDateTime.now());
        addOrders.setOrderTime(LocalDateTime.now());
        addOrders.setPayMethod(1);
        addOrders.setUserId(userId);
        addOrders.setUserName(userService.getById(BaseContext.getCurrentId()).getName());
        addOrders.setRemark(orders.getRemark());
        addOrders.setStatus(2);
        addOrders.setPhone(addressBook.getPhone());
        addOrders.setSumNum(carts.size());                      //包含商品数量数据
        ordersList.add(addOrders);

        this.saveBatch(ordersList);
        shoppingCartService.remove(cartqw);
    }

    @Override
    public Page<Orders> paginationQuery(Integer page, Integer pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<Orders> oP = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(null != number,Orders::getNumber,number);
        qw.between(null != beginTime && null != beginTime,Orders::getOrderTime,beginTime,endTime);
        Page<Orders> orders = this.page(oP, qw);
        orders.getRecords().stream().map((item)->{
            Long userId = item.getUserId();
            item.setUserName(userService.getById(userId).getName());
            return item;
        }).count();             //使用count方法来结束流 保证流中操作的结果可以保留
        return orders;
    }

    @Override
    public Boolean updStateInfo(Orders orders) {

        if (orders == null && "".equals(orders.toString())) throw new CustomException("参数异常!!");

        LambdaUpdateWrapper<Orders> uw = new LambdaUpdateWrapper<>();
        uw.set(Orders::getStatus,orders.getStatus());
        uw.eq(Orders::getId,orders.getId());

        return this.update(uw);
    }

    @Override
    public Page<Orders> userPage(Integer page, Integer pageSize) {
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,BaseContext.getCurrentId());
        //将最新(最大时间)订单时间放在最上面 降序
        qw.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        this.page(ordersPage, qw);
        return ordersPage;
    }

    /**
     * 再来一单接口服务层实现
     * @param orders
     */
    @Override
    public void comeAgain(Orders orders) {
        if (null == orders && "".equals(orders.toString())) throw new CustomException("传入的订单对象为null");
        Long orderId = orders.getId();
        LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(null != orderId,OrderDetail::getOrderId,orderId);
        List<OrderDetail> details = orderDetailService.list(qw);        //返回订单下所属商品集合
        for (int i = 0; i < details.size(); i++) {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(details.get(i),cart,"id");
            cart.setUserId(BaseContext.getCurrentId());
            shoppingCartService.add(cart);
        }
    }
}
